package candidature.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import util.FtpFileSender;
/**
 * Servlet implementation class UploadFile
 */
public class UploadFile extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger logger=LogManager.getLogger(this.getClass());
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadFile() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException{
    	logger.info("BEGIN - UploadFile");
    	OutputStream os = null;
    	PrintWriter out = response.getWriter();
    	try {
    		
    		 ResourceBundle rb= ResourceBundle.getBundle("bundle");
    	        
    	        
    		// Create a factory for disk-based file items
    		FileItemFactory factory = new DiskFileItemFactory();

    		// Create a new file upload handler
    		ServletFileUpload upload = new ServletFileUpload(factory);
    		
    		String skill = request.getParameter("skill_parameter");
    		    		
    		logger.debug("--AAAAAAAAA "+skill);
    		
    		// Parse the request
    		List  <FileItem> items = upload.parseRequest(request);
    		
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                    String fieldname = item.getFieldName();
                    String fieldvalue = item.getString();
                    // ... (do your job here)
                } else {
                    // Process form file field (input type="file").
                    String fieldname = item.getFieldName();
                    String filename = FilenameUtils.getName(item.getName());
                    InputStream filecontent = item.getInputStream();
                    
                    int m = filecontent.read();
                    
                    URL url = null;
                    URLConnection urlc = null;
                    
                    String path=getServletContext().getRealPath("/temp_files");
                    
                    Date d=new Date();
                    
                    SimpleDateFormat df=new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
                  
                    String dateString=df.format(d);
                    
                    String filePath=path+"/"+dateString+"_"+filename;
                    
                    File f=new File(filePath);
                    
//                    url = f.toURI().toURL();
//                    urlc = url.openConnection();
                    
                    os = new FileOutputStream(f);
                    
                    while(m != -1)
                    {
                        os.write(m);
                        m = filecontent.read();
                    }
                    filecontent.close();
//                    InputStream response = urlc.getInputStream();
//                    byte[] buffer = new byte[1000];
//                    while(response.read(buffer) != -1)
//                    {
//                    }
                    
                    // ... (do your job here)
                    
                    String head= "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'>" +
                    "<title>Opener</title>"; 
                    
                    StringBuffer script= new StringBuffer();
                    script.append("<script type='text/javascript'>");
                    script.append("function validepopupform(){");
                    script.append("window.opener.document.getElementById('cv').value=document.getElementById('uploaded_cv_file').value;");
                    
                    String domain = rb.getString("FTP_DOMAIN");
                    String user = rb.getString("FTP_USER");
                    String password = rb.getString("FTP_PASSWORD");
                    String outputPath =rb.getString("FTP_OUTPUT_PATH");
                    String outputFolder =rb.getString("FTP_OUTPUT_FOLDER");
                    
                    String ftpRoot= rb.getString("FTP_ROOT");
                    String joomlaPath =rb.getString("JOOMLA_STD_FOLDER");
                    
                    FtpFileSender ftpFileSender =new FtpFileSender(domain, user, password, f, outputPath);
                    
                    if(!ftpFileSender.checkFolder(skill)){
                    	ftpFileSender.createFolder(skill);
                    }
                    ftpFileSender.sendFile(skill);
                    f.delete();
                    
//                    logger.debug("check folder existance ");
                    
//                    script.append("window.opener.document.getElementById('new_cv').value='1'") ;
//                    "alert('test2');" +
                    script.append("self.close();") ;
                    script.append("}</script></head><body onload='validepopupform()'>"); 
                    
                    ;
                    
                    String tail="</body></html> " ;
                    		
                    
                    filename= joomlaPath+outputFolder+skill+"/"+dateString+"_"+filename;
                    String output=head+script+"<p>File"+filename+" Caricato</p>" +
                    		"<input type='hidden' value='"+filePath+"' id='uploaded_cv_path' />" +
                    		"<input type='hidden' value='"+filename+"' id='uploaded_cv_file' />" +
                    		
                    		tail
                    		;
                    
                    out.print(output);
                    
                }
            }
        } catch (FileUploadException e) {
            logger.error("Errore nel caricamento del CV", e);
            out.print("<p>Caricamento del CV fallito</p>");
        }
        finally
        {
        	 if(os != null)
             {
                 os.flush();
                 os.close();
             }
        	 out.close();
        }
            
           
    	
    	logger.info("END - UploadFile");
    }
    	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
}
